#include <alsa/asoundlib.h>
#include <iostream>
#include <fstream>

#define PCM_DEVICE "default"//默认的播放设备,你可以在settings里面调换

int main(int argc, char *argv[]) {
    const char *audioFilename = "/test.pcm";

    // 配置ALSA参数
    snd_pcm_t *pcmHandle;
    if (snd_pcm_open(&pcmHandle, PCM_DEVICE, SND_PCM_STREAM_PLAYBACK, 0) < 0) {
        std::cerr << "Error: Failed to open PCM device" << std::endl;
        return 1;
    }

    snd_pcm_hw_params_t *params;
    snd_pcm_hw_params_alloca(&params);
    snd_pcm_hw_params_any(pcmHandle, params);
    snd_pcm_hw_params_set_access(pcmHandle, params, SND_PCM_ACCESS_RW_INTERLEAVED);
    snd_pcm_hw_params_set_format(pcmHandle, params, SND_PCM_FORMAT_S16_LE);
    snd_pcm_hw_params_set_channels(pcmHandle, params, 2);
    unsigned int sampleRate = 16000;
    snd_pcm_hw_params_set_rate_near(pcmHandle, params, &sampleRate, nullptr);
    snd_pcm_uframes_t bufferSize = 512;
    snd_pcm_hw_params_set_buffer_size_near(pcmHandle, params, &bufferSize);
    snd_pcm_hw_params(pcmHandle, params);

    std::ifstream ifs("./test.cpm");
    if (ifs.is_open()) {
        std::string data;
        size_t size;
        char buffer[8192];
        while ((size = ifs.readsome(buffer, 8192)) > 0) {
            data.append(buffer, size);
        }
        snd_pcm_sframes_t err = snd_pcm_writei(pcmHandle, (const void *) data.c_str(),
                                               data.size()); 
        if (err < 0) {
            std::cerr << "Error: Failed to write PCM device" << std::endl;
        }
        ifs.close();
    }

    // 关闭PCM设备和文件
    snd_pcm_close(pcmHandle);
    return 0;
}
